import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:二叉树的层序遍历
 * User: liangyuanzhang
 * Date: 2025-4-26
 * Time: 23:48
 */
public class leveOrder {
    public List<List<Integer>> leveOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();//二维数组
        if (root == null){
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);//入队
        while (!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list = new ArrayList<>(); //一维数组
            while (size!=0){
                TreeNode cur = queue.poll();
                list.add(cur.val);
                if (cur.left != null){
                    queue.offer(cur.left);
                }
                if (cur.right != null){
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }
}
